import { defineStore } from 'pinia';
import { Session } from '/@/utils/storage';
import { useLoginApi } from '/@/api/login';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			uid: 0,
			userName: '',
			photo: '',
			time: 0,
			roles: [],
			authBtnList: [],
			customer: {},
			tenant: {}
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				const userInfos = <UserInfos>await this.getApiUserInfo();
				this.userInfos = userInfos;
				Session.set('userInfo', userInfos);
			}
		},

		async getApiUserInfo() {
			return useLoginApi()
				.getUserByToken({})
				.then((res: any) => {
					if (!res.success){
						return false;
					}
					const data = res.data;
					const userInfos = {
						userName: data.RealName,
						uid: data.Id,
						photo: data.avatar,
						time: new Date().getTime(),
						roles: [data.roles],
						authBtnList: ['btn.add', 'btn.del', 'btn.edit', 'btn.link'],
						customer: data.customer,
						tenant: data.tenant,
					};
					return userInfos;
				})
				.catch((err: any)=> {
					console.log(err)
				});
			}
		},
});
